package com.arrays;

//滑动窗口内只能有两种元素
public class FruitIntoBaskets0125_904 {
/**
 * 滑动窗口
 * 初始：左指针left、右指针right、左类型lType、右类型rType，
 *      维护左右指针，左右类型，
 *
 */
//    public int totalFruit(int[] fruits) {
//
//        int res = 0;
//        int left = 0, right = 0, lType = fruits[left], rType = fruits[right];
//
//        while (right < fruits.length){
//            if(fruits[right] == lType || fruits[right] == rType){
//                res = Math.max(res, right-left+1);
//                right++;
//            }else {
//                rType = fruits[right];
//                left = right - 1; //!!!!!!!!!!!!
//                lType = fruits[left];
//                while (left >=1 && fruits[left - 1] == lType) left--;
//                res = Math.max(res, right -left +1);
//            }
//        }
//        return res;
//    }

    public int totalFruit(int[] fruits) {
        int[] window = new int[fruits.length];
        int l = 0, r = 0, ans = 0, same = 0;
        while (r < fruits.length) {
            if (window[fruits[r++]]++ == 0)
                same++;
            while (same > 2) {
                if (window[fruits[l++]]-- == 1)
                    same--;
            }
            ans = Math.max(r - l, ans); //!!!!!!!!!
        }
        return ans;
    }
}
